package com.example.springbootes.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.springbootes.entity.Book;
import org.apache.http.HttpEntity;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author lisg
 * @description
 * @createTime 2022/3/3
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Resource
    private RestHighLevelClient client;

    /**
     * 数据添加到ES
     * @param book
     * @return
     * @throws IOException
     */
    @PostMapping("/add")
    public Boolean addBook(@RequestBody Book book) throws IOException {
        IndexRequest request = new IndexRequest("book","test");
        request.timeout("1s");
        request.source(JSONObject.toJSONString(book), XContentType.JSON);

        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println("添加文档："+JSONObject.toJSONString(book));
        Boolean created = response.getResult().getLowercase().equals("created");
        return created;
    }

    /**
     * 删除数据
     * @param index 索引
     * @param type  类型
     * @param id    id
     * @return
     * @throws IOException
     */
    @DeleteMapping("/{index}/{type}/{id}/delete")
    public String deleteBook(@PathVariable("index") String index,
                                 @PathVariable("type") String type,
                                 @PathVariable("id") String id) throws IOException{
        DeleteRequest deleteRequest = new DeleteRequest(index, type, id);
        deleteRequest.timeout("1s");
        DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println("删除文档："+response.status());
        return response.status().toString();
    }

    /**
     * 删除
     * @param book  实体类
     * @param id    id
     * @return
     * @throws IOException
     */
    @PostMapping("/update")
    public String updateBook(@RequestBody Book book, @RequestParam(value = "id") String id) throws IOException{
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index("book").type("test").timeout("1s").id(id).doc(JSONObject.toJSONString(book), XContentType.JSON);
        UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println("修改文档："+response.status());
        return response.status().toString();
    }

    /**
     * 查询所有书籍
     * @return
     * @throws IOException
     */
    @GetMapping("/list")
    public List<Book> getBooks() throws IOException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(0).size(100).timeout(new TimeValue(60, TimeUnit.SECONDS));
        // sourceBuilder.fetchSource(new String[] {"fields.name", "fields.sex", "fields.age"}, new String[] {});
        SearchRequest searchRequest = new SearchRequest("book");
        searchRequest.types("test").source(sourceBuilder);
        SearchResponse resp = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = resp.getHits();
        SearchHit[] searchHits = hits.getHits();
        List<Book> bookList = new ArrayList<>();
        for (SearchHit searchHit : searchHits) {
            String aa = searchHit.getSourceAsString();
            Book book = JSONObject.parseObject(searchHit.getSourceAsString(), Book.class);
            System.out.println(book);
            bookList.add(book);
        }
        return bookList;
    }
}
